package club.koorikaze;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class dom41 {
    @Test
    public void read() throws Exception {


        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/club/koorikaze/one.xml"));

        //得到根节点
        Element root = document.getRootElement();


        //得到根节点下的制定子节点并遍历
        List nodes = root.elements("people");
//        Element people = root.elements("people").get(1);
        //这样也可以，单个节点就没有s

        for (Iterator it = nodes.iterator();it.hasNext();) {
            Element people = (Element) it.next();
//            String value =  people.element("name").getText();
//            System.out.print(value);
            System.out.println(people.element("pname").getText());
        }
    }

    @Test
    public void readall() throws Exception {

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("src/club/koorikaze/one.xml"));

        Element rootele = document.getRootElement();

        Element itemele = null;

        for (Iterator it = rootele.elementIterator()/*遍历每个子节点*/; it.hasNext(); ) {
            itemele = (Element) it.next();
//            System.out.println(itemele.getName());
        }

    List listele = rootele.elements(itemele.getName());

        for (Iterator it = listele.iterator() ; it.hasNext();) {
            Element item = (Element) it.next();

            for (Iterator it2 = item.elementIterator()/*遍历每个子节点*/; it2.hasNext(); ) {
                itemele = (Element) it2.next();
            System.out.println(itemele.getName());
            }

//            System.out.print(item.getText());
            System.out.println("");
        }
    }

    @Test
    public void readname() throws Exception {

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(new File("src/club/koorikaze/one.xml"));
        Element root = document.getRootElement();

        Element first = root.elements("people").get(0);

        Element first1 = first.element("pname");

        System.out.println(first1.getName());
        System.out.println(first1.getText());

        for (Iterator it = first1.attributeIterator() ; it.hasNext() ; ) {
            Attribute attribute = (Attribute) it.next();

            System.out.println(attribute.getName());
            System.out.println(attribute.getText());
        }

//        System.out.println();
    }

}
